package top.houry.netty.barrage.rocketmq;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;


/**
 *
 * RocketMQ
 *  生产者
 *  异步存db
 */
@Component
@Slf4j
public class ProducerService implements ApplicationContextAware {
    final static String nameServerUrl = "127.0.0.1:9876";
    final static String ProducerGROUP = "test-producer";

    private DefaultMQProducer mqProducer;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        startMQProducer();
    }

    /**
     *
     * 启动生产者
     */
    synchronized private void startMQProducer() {
        // 指定生产者 组名
        mqProducer = new DefaultMQProducer(ProducerGROUP);
        // 配置nameServer地址
        mqProducer.setNamesrvAddr(nameServerUrl);
        try {
            mqProducer.start();
            log.info("生产者已经启动！");
        } catch (MQClientException e) {
            log.warn("生产者启动失败！ 原因：{}",e.getErrorMessage());
            e.printStackTrace();
        }
    }

    /**
     *         // 创建消息
     *         Message message = new Message(topic,"弹幕消息-测试".getBytes(StandardCharsets.UTF_8));
     *同步发送消息
     */
    public void sendMessage(Message message){
        try {
            mqProducer.send(message);
        } catch (Exception e) {
            e.printStackTrace();
            log.warn("消息发送失败！ ");
        }
    }
}
